import { Injectable, HttpException } from '@nestjs/common';
import { CreateFileDto } from './dto/create-file.dto';
import { UpdateFileDto } from './dto/update-file.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { File } from './entities/file.entity';
import {
  PaginationService,
  PaginationResult,
} from '../../common/pagination/pagination.service';
import { diskStoragePath } from '../../utils/constant';

@Injectable()
export class FileService {
  constructor(
    @InjectRepository(File)
    private readonly fileRepository: Repository<File>,
    private pageService: PaginationService<File>,
  ) {
    this.pageService = new PaginationService<File>(this.fileRepository);
  }

  async upload(file: Express.Multer.File, digest: string, fileName: string) {
    const name = decodeURIComponent(fileName);
    // console.log('upload-name-digest',name, digest);
    const pathStr = file.path.replace(/\\/g, '/');
    const paths = pathStr.split(diskStoragePath);
    // console.log('文件本地路径:==>',pathStr, paths);
    const data: CreateFileDto = {
      name: name,
      originalname: name,
      size: file.size + '',
      url: `/${diskStoragePath}${paths.at(-1)}`,
      mime: file.mimetype,
      hash: digest,
    };
    console.log('文件上传', file, data);
    return await this.create(data);
  }

  async create(createFileDto: CreateFileDto) {
    const data = this.fileRepository.create(createFileDto);
    return await this.fileRepository.save(data);
  }

  async findAll(params: { page: number; pageSize: number; name: string }) {
    const where = {};
    if (params.name) {
      where['name'] = params.name;
    }
    const res = await this.pageService.paginate({
      ...params,
      options: { where },
    });
    return res;
  }

  // 分页查询接口
  pageSearch(params: { page: number; pageSize: number; name: string }) {
    // 定义查询构造器
    const queryBuilder = this.fileRepository.createQueryBuilder();
    // 模糊查询name字段
    if (params.name) {
      queryBuilder.where('name like :name', { name: `%${params.name}%` })
    }
    // 分页查询
    return this.pageService.pageSearch({
      page: params.page,
      pageSize: params.pageSize,
      queryBuilder,
    });
  }

  async findOne(id: string) {
    return await this.fileRepository.findOneBy({ id });
  }

  async update(id: string, updateFileDto: UpdateFileDto) {
    const data = await this.findOne(id);
    if (!data) throw new HttpException('数据不存在', 400);
    const updateData = this.fileRepository.merge(data, updateFileDto);
    return await this.fileRepository.save(updateData);
  }

  async remove(id: string) {
    const data = await this.findOne(id);
    if (!data) throw new HttpException('数据不存在', 400);
    return await this.fileRepository.delete({ id });
  }

  async getFileByDigest(digest: string) {
    return await this.fileRepository.findOne({ where: { hash: digest } });
  }
}
